<template>
  <el-dialog v-model="visible" title="数据库结构查询" width="45%" :before-close="handleClose">
    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center p-4 min-h-[200px]">
      <el-loading />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="text-red-500 p-4">
      {{ error }}
    </div>

    <!-- 正常状态 -->
    <template v-else>
      <!-- 数据库信息 -->
      <div class="mb-6">
        <span class="font-semibold mr-2">数据库：</span>
        <el-text type="danger">{{ schemaData?.database }}</el-text>
      </div>

      <!-- 表格列表 -->
      <div v-for="table in schemaData?.tables" :key="table.table_name" class="mb-8">
        <!-- 表头 -->
        <div class="flex items-baseline gap-3 mb-3">
          <span class="font-semibold">表名:</span>
          <div class="flex items-baseline gap-2">
            <el-text type="primary" tag="strong">{{ table.table_name }}</el-text>
            <el-text v-if="table.comments" type="success" class="text-sm">
              ({{ table.comments }})
            </el-text>
          </div>
        </div>

        <!-- 字段表格 -->
        <el-table :data="table.columns" border stripe class="custom-table">
          <el-table-column prop="column_name" label="字段名" width="180" />
          <el-table-column prop="comments" label="注释" width="200" show-overflow-tooltip />
          <el-table-column prop="data_type" label="数据类型" width="200" align="center" />
          <el-table-column label="主键" width="127" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.is_primary_key" type="success">
                是
              </el-tag>
              <span v-else class="text-gray-500">否</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElDialog, ElTable, ElTableColumn, ElTag, ElLoading } from 'element-plus'
import { getSchemaJson } from '../services/schemaService'

const visible = ref(false)
const loading = ref(false)
const error = ref('')
const schemaData = ref(null)

const loadSchemaData = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await getSchemaJson()
    if (response.success) {
      schemaData.value = response.data.schema
    } else {
      error.value = response.msg || '获取数据结构失败'
    }
  } catch (err) {
    error.value = '获取数据结构失败：' + (err.message || '未知错误')
  } finally {
    loading.value = false
  }
}

const show = async () => {
  visible.value = true
  await loadSchemaData()
}

const handleClose = () => {
  visible.value = false
}

defineExpose({
  show
})
</script>
